package cn.itcast.search.servicer.serviceImpe;

import cn.itcast.feign.client.ItemClient;
import cn.itcast.hmall.dto.common.PageDTO;
import cn.itcast.hmall.dto.common.ResultDTO;
import cn.itcast.hmall.dto.item.SearchItemDTO;
import cn.itcast.hmall.dto.search.SearchReqDTO;
import cn.itcast.hmall.pojo.item.Item;
import cn.itcast.hmall.pojo.item.ItemDoc;
import cn.itcast.search.servicer.Serviceiten;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

@Service
public class ServiceImpe implements Serviceiten {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    ItemClient itemClient;

    //导入数据到es
    @Override
    public ResultDTO listItemAdds() {
        try {
            SearchItemDTO searchItemDTO = new SearchItemDTO();
            Integer page = 1, size = 500;
            searchItemDTO.setPage(page);
            searchItemDTO.setSize(size);
            //远程调用item方法
            PageDTO<Item> selectitmlist = itemClient.selectitmlist(searchItemDTO);
            //总条数
            int total = selectitmlist.getTotal().intValue();
            //分批插入，按查询分页的数量查询一次性插入500，为了防止最后页有数据丢失加500天空间
            for (; page * size < total + size; page++) {
                //吧当前页给分页的开始页数，形成循环查询效果
                searchItemDTO.setPage(page);
                //那到具体的数据
                List<Item> list = itemClient.selectitmlist(searchItemDTO).getList();
                //这样参数就可以跟根据对应的页数拿出数据
                //创建批量添加请求对象
                BulkRequest bulkRequest = new BulkRequest();
                for (Item item : list) {
                    //循环但插入
                    ItemDoc itemDoc = new ItemDoc(item);
                    bulkRequest.add(new IndexRequest("item").id(itemDoc.getId() + "").
                            source(JSON.toJSONString(itemDoc), XContentType.JSON));
                }

                client.bulk(bulkRequest, RequestOptions.DEFAULT);
            }
            return ResultDTO.ok();

        } catch (IOException e) {
            throw new RuntimeException("参数异常");
        }


    }

    @Override
    public List<String> entrtSear(String entry) {
        try {
            //创建请求
            SearchRequest item = new SearchRequest("item");
            //添加suggest搜索条件
            SearchSourceBuilder source = item.source();
            source.suggest(
                    new SuggestBuilder().addSuggestion("mySiggestion",//自定义词条
                            SuggestBuilders.
                                    completionSuggestion("suggestion").
                                    prefix(entry)//匹配对应的词条
                                    .skipDuplicates(true).//去除重复词条
                                    size(10)//保存10条

                    )
            );

            //执行请求
            SearchResponse search = client.search(item, RequestOptions.DEFAULT);
            //查询suggest结果
            Suggest suggest = search.getSuggest();
            //获取指定的结果
            CompletionSuggestion suggestion = suggest.getSuggestion("mySiggestion");
            //获取options 便利
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> strings = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : options) {
                strings.add(option.getText().toString());
            }
            return strings;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("自动补全失败");
        }
    }


    @Override
    public Map<String, List<String>> theAggregation(SearchReqDTO searchReqDTO) {
        try {
            SearchRequest item = new SearchRequest("item");
            SearchSourceBuilder source = item.source();
            bulidBasicQuer(searchReqDTO, source);
            source.size(0);
            buildAggregation(item);

            SearchResponse search = client.search(item, RequestOptions.DEFAULT);
            HashMap<String, List<String>> objectObjectHashMap = new HashMap<>();
            Aggregations aggregations = search.getAggregations();
            List<String> categoryAgg = listname(aggregations, "categoryAgg");
            objectObjectHashMap.put("category", categoryAgg);
            List<String> brandAggs = listname(aggregations, "brandAgg");
            objectObjectHashMap.put("brand", brandAggs);
            return objectObjectHashMap;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public PageDTO<ItemDoc> selectlist(SearchReqDTO searchReqDTO) {
        try {
            SearchRequest searchRequest = new SearchRequest("item");
            SearchSourceBuilder source = searchRequest.source();
            bulidBasicQuer(searchReqDTO, source);
            //设置分页
            Integer page = searchReqDTO.getPage();
            Integer size = searchReqDTO.getSize();
            source.from((page - 1) * size);
            source.size(size);
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("all");
            highlightBuilder.preTags("<em>");
            highlightBuilder.postTags("</em>");
            highlightBuilder.requireFieldMatch(false);
            source.highlighter(highlightBuilder);
            //销量
            if (searchReqDTO.getSortBy().equals("sold")) {
                source.sort("sold", SortOrder.DESC);
            } else if (searchReqDTO.getSortBy().equals("price")) {
                source.sort("price", SortOrder.ASC);
            }
            //提交请求获取返回参数
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            //查询条数
            long value = hits.getTotalHits().value;
            List<ItemDoc> itemDocs = new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
                itemDoc.setPrice(itemDoc.getPrice() * 100);
                //高亮效果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(highlightFields)) {
                    HighlightField name = highlightFields.get("all");
                    String join = StringUtils.join(name.getFragments());
                    itemDoc.setName(join);
                }
                itemDocs.add(itemDoc);
            }
            return new PageDTO<>(value, itemDocs);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }



    //根据消息mq信息添加
    @Override
    public void additem(Long id) {
        try {
        Item item = itemClient.additem(id.toString());
        ItemDoc itemDoc = new ItemDoc(item);
        IndexRequest indexRequest = new IndexRequest("item").id(item.getId().toString());
        indexRequest.source(JSON.toJSONString(itemDoc), XContentType.JSON);

            client.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //根据消息mq删除
    @Override
    public void deleteitem(Long id) {
        try {
        DeleteRequest item = new DeleteRequest("item", id.toString());

            DeleteResponse delete = client.delete(item, RequestOptions.DEFAULT);
            System.out.println("下架成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public List<String> listname(Aggregations aggregations, String aggName) {
        Terms categoryAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = categoryAgg.getBuckets();
        List<String> objects = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String keyAsString = bucket.getKeyAsString();
            objects.add(keyAsString);
        }
        return objects;
    }

    public void buildAggregation(SearchRequest request) {
        //聚合
        request.source().aggregation(AggregationBuilders.
                terms("categoryAgg").
                field("category").
                size(50));
        request.source().aggregation(AggregationBuilders.
                terms("brandAgg").
                field("brand").
                size(50));

    }
//分页查询


    public void bulidBasicQuer(SearchReqDTO searchReqDTO, SearchSourceBuilder source) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String key = searchReqDTO.getKey();
        if (key == null || "".equals(key)) {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        } else {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }
        if (searchReqDTO.getCategory() != null && !searchReqDTO.getCategory().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", searchReqDTO.getCategory()));
        }
        if (searchReqDTO.getBrand() != null && !searchReqDTO.getBrand().equals("")) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", searchReqDTO.getBrand()));
        }
        if (searchReqDTO.getMinPrice() != null && searchReqDTO.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(searchReqDTO.getMinPrice()).lte(searchReqDTO.getMaxPrice()));
        }
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )

                }

        ).boostMode(CombineFunction.MULTIPLY);
        source.query(boolQueryBuilder);
        source.query(functionScoreQueryBuilder);

    }


}




